package com.ctgu.swzl.controller;

import com.ctgu.swzl.dao.CommentDao;
import com.ctgu.swzl.dao.NoticeDao;
import com.ctgu.swzl.domain.Comment;
import com.ctgu.swzl.domain.Notice;
import com.ctgu.swzl.domain.Post;
import com.ctgu.swzl.domain.Type;
import com.ctgu.swzl.service.PostService;
import com.ctgu.swzl.service.TypeService;
import com.ctgu.swzl.utils.SimpleJson;
import com.ctgu.swzl.vo.TypeVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class PostController {

    @Value("${images.path}")
    private String path;

    @Autowired
    private PostService postService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private SimpleJson simpleJson;

    @Autowired
    private NoticeDao noticeDao;

    @GetMapping("/index")
    public String getPost(@RequestParam(value = "status",required = false)Integer status,
                          @RequestParam(value = "flag",required = false) Integer flag,
                          @RequestParam(value = "type",required = false) String typeName,
                          @RequestParam(value = "search",required = false) String search,
                          @RequestParam(value = "page",required = false) Integer page){
        // 构建查询参数字符串
        StringBuilder params = new StringBuilder();
        
        if (status != null) {
            params.append("status=").append(status).append("&");
        }
        if (flag != null) {
            params.append("flag=").append(flag).append("&");
        }
        if (typeName != null && !typeName.isEmpty()) {
            params.append("type=").append(typeName).append("&");
        }
        if (search != null && !search.isEmpty()) {
            params.append("search=").append(search).append("&");
        }
        if (page != null) {
            params.append("page=").append(page).append("&");
        }
        
        // 去掉最后的&符号
        if (params.length() > 0) {
            params.setLength(params.length() - 1);
        }
        
        return "forward:/indexFilter?" + params.toString();
    }

    @GetMapping("/index/{status}/{flag}/{typeName}")
    public ModelAndView getAppoint(@PathVariable("status")int status,
                                   @PathVariable("flag")int flag,
                                   @PathVariable("typeName") String tname,
                                   @RequestParam(value = "search",required = false)String search,
                                   @RequestParam(value = "page",required = false)Integer page){
        // 重定向到新的统一筛选方法
        StringBuilder redirectUrl = new StringBuilder("redirect:/index?");
        
        if (status != 2) {
            redirectUrl.append("status=").append(status).append("&");
        }
        if (flag != 2) {
            redirectUrl.append("flag=").append(flag).append("&");
        }
        if (!"false".equals(tname)) {
            redirectUrl.append("type=").append(tname).append("&");
        }
        if (search != null) {
            redirectUrl.append("search=").append(search).append("&");
        }
        if (page != null) {
            redirectUrl.append("page=").append(page);
        }
        
        return new ModelAndView(redirectUrl.toString());
    }

    @GetMapping("/indexFilter")
    public ModelAndView getFilteredPosts(@RequestParam(value = "status",required = false) Integer status,
                                       @RequestParam(value = "flag",required = false) Integer flag,
                                       @RequestParam(value = "type",required = false) String typeName,
                                       @RequestParam(value = "search",required = false) String search,
                                       @RequestParam(value = "page",required = false) Integer page){
        // 添加调试输出
        System.out.println("收到参数 - typeName: '" + typeName + "'");
        
        List<Post> posts = new ArrayList<>();
        ModelAndView modelAndView = new ModelAndView();

        int pageSize=4;
        if (page==null) {
            page=1;
        }
        Page<Object> pages = PageHelper.startPage(page, pageSize,"ctime desc");

        // 获取所有帖子作为基础数据
        posts = postService.findAll();
        String message = "启事";

        // 按状态和类型筛选
        if (status != null && flag != null) {
            posts = posts.stream()
                    .filter(post -> post.getStatus() == status && post.getFlag() == flag)
                    .collect(Collectors.toList());
            
            if (status == 0 && flag == 0) {
                message = "已经找到";
            } else if (status == 0 && flag == 1) {
                message = "已被认领";
            } else if (status == 1 && flag == 0) {
                message = "正在寻找";
            } else if (status == 1 && flag == 1) {
                message = "等待认领";
            }
        }

        // 按分类筛选
        if (typeName != null && !typeName.isEmpty()) {
            // 检查是否包含重复的分类名（用逗号分隔）
            String actualTypeName = typeName;
            if (typeName.contains(",")) {
                // 如果包含逗号，取第一个分类名
                actualTypeName = typeName.split(",")[0];
                System.out.println("检测到重复分类，使用: '" + actualTypeName + "'");
            }
            
            final String finalTypeName = actualTypeName;
            posts = posts.stream()
                    .filter(post -> finalTypeName.equals(post.getTypeName()))
                    .collect(Collectors.toList());
            
            if (status != null && flag != null) {
                message = message + " - " + actualTypeName;
            } else {
                message = actualTypeName;
            }
        }

        // 按搜索关键字筛选
        if (search != null && !search.isEmpty()) {
            posts = posts.stream()
                    .filter(post -> post.getContent().contains(search) || post.getTitle().contains(search))
                    .collect(Collectors.toList());
            message = "根据关键字<" + search + ">找到如下记录";
            pages.setTotal(posts.size());
        }

        // 分页处理
        PageInfo<Post> pageInfo = new PageInfo<Post>(posts);
        pageInfo.setPageNum(page);
        pageInfo.setPages(pageSize);
        int a = (int)pages.getTotal()%pageSize==0?0:1;
        pageInfo.setPages((int)pages.getTotal()/pageSize+a);
        pageInfo.setPrePage(page-1);
        pageInfo.setNextPage(page+1);

        // 构建类型统计和状态统计
        List<Type> types = typeService.findAll();
        List<TypeVO> list = new ArrayList<>();
        for (Type type : types) {
            TypeVO typeVO = new TypeVO();
            String typeNameStr = type.getTypeName();
            typeVO.setName(typeNameStr);
            typeVO.setCount(typeService.getCountByName(typeNameStr));
            list.add(typeVO);
        }
        
        List<Integer> SL = new ArrayList<>();
        List<Notice> notices = noticeDao.findAll();
        SL.add(postService.findBySL(1,0).size()); //正在寻找
        SL.add(postService.findBySL(0,0).size()); //已经找到
        SL.add(postService.findBySL(1,1).size()); //等待认领
        SL.add(postService.findBySL(0,1).size()); //已被认领
        
        modelAndView.addObject("postList",posts);
        modelAndView.addObject("typeList",list);
        modelAndView.addObject("notices",notices);
        modelAndView.addObject("SL",SL);
        modelAndView.addObject("pageInfo",pageInfo);
        modelAndView.addObject("message", message);
        modelAndView.addObject("currentStatus", status);
        modelAndView.addObject("currentFlag", flag);
        // 确保传递的是处理后的分类名
        modelAndView.addObject("currentType", typeName != null && typeName.contains(",") ? typeName.split(",")[0] : typeName);
        modelAndView.addObject("currentSearch", search);
        
        // 添加用于判断是否有筛选条件的标志
        boolean hasFilters = (status != null) || (flag != null) || (typeName != null && !typeName.isEmpty());
        modelAndView.addObject("hasFilters", hasFilters);
        
        modelAndView.setViewName("index");
        return modelAndView;
    }

    @GetMapping("/doSearch")
    public String doSearch(@RequestParam("content")String content,
                          @RequestParam(value = "status",required = false) Integer status,
                          @RequestParam(value = "flag",required = false) Integer flag,
                          @RequestParam(value = "type",required = false) String type){
        StringBuilder params = new StringBuilder("redirect:/index?search=" + content);
        
        if (status != null) {
            params.append("&status=").append(status);
        }
        if (flag != null) {
            params.append("&flag=").append(flag);
        }
        if (type != null && !type.isEmpty()) {
            params.append("&type=").append(type);
        }
        
        return params.toString();
    }

    @GetMapping("/announce")
    public ModelAndView toAnnounce(){
        List<Type> types = typeService.findAll();
        ModelAndView mv = new ModelAndView();
        mv.addObject("types",types);
        mv.setViewName("announce.html");
        return mv;
    }

    @PostMapping("/announce")
    public String addPost(HttpServletRequest request,
                          Post post,
                          @RequestParam("fruit") String xr,
                          MultipartFile upload) throws IOException {
        String uname = (String) request.getSession().getAttribute("loginUser");
        int flag = xr.equals("x")?0:1;
        post.setUname(uname).setFlag(flag).setStatus(1).setCtime(new Date());
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        String filename = upload.getOriginalFilename();
        filename = UUID.randomUUID().toString().replaceAll("-","")+"_"+filename;
        upload.transferTo(new File(path,filename));
        post.setPicture("/images/"+filename);
        postService.addPost(post);
        return "redirect:/index";
    }


    @GetMapping("/detail")
    public ModelAndView toDetail(@RequestParam("postId")Long postId){
        ModelAndView modelAndView = new ModelAndView();
        Post post = postService.findById(postId).get(0);
        modelAndView.addObject("post",post);
        modelAndView.setViewName("detail");
        post.setViewCount(post.getViewCount()+1);
        postService.updateViewCount(post);
        return modelAndView;
    }

    @ResponseBody
    @PostMapping("/updateMyPostStatus")
    public String updateMyPostStatus(@RequestParam("postId") long postId,
                                   @RequestParam("status") int status,
                                   HttpServletRequest request) {
        String currentUser = (String) request.getSession().getAttribute("loginUser");
        if (currentUser == null) {
            return "0"; // 用户未登录
        }
        
        Post post = postService.findById(postId).get(0);
        if (post == null || !post.getUname().equals(currentUser)) {
            return "2"; // 帖子不存在或不是用户自己的帖子
        }
        
        post.setStatus(status);
        postService.updateStatus(post);
        return "1"; // 修改成功
    }

    @ResponseBody
    @PostMapping("/addcomment")
    public String addComment(@RequestParam("comment") String comment,
                            @RequestParam("postId") long postId,
                            @RequestParam("parentId")long parentId,
                            HttpServletRequest request) {
        Object loginUser = request.getSession().getAttribute("loginUser");
            if (loginUser==null){
                return "0";
        }
        Comment newComment = new Comment();
        String uname = (String) request.getSession().getAttribute("loginUser");
        newComment.setUname(uname)
                .setContent(comment)
                .setPostId(postId)
                .setCtime(new Date())
                .setParent(parentId);
        if (parentId==0){
            commentDao.addComment0(newComment);
        }else {
            commentDao.addComment(newComment);
        }
        return "1";
    }
}
